import React, { useEffect, useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import AuthorityButton from '@/components/AuthorityButton';
import ModalForm from './components/ModalForm';
import { useIntl } from 'umi';
import { message } from 'antd';
import { page, del, getRoleList, getOrgTre } from './service';

const Tenant = () => {
  const actionRef = useRef();
  const formRef = useRef();
  const [currentRow, setCurrentRow] = useState({});
  // 显示控制
  const [modalVisit, setModalVisit] = useState(false);
  const [state, setState] = useState('read');
  const [roleLis, setRoleLis] = useState([]);
  const [orgTre, setOrgTre] = useState([]);
  //初始化数据
  useEffect(() => {
    const initData = async (value) => {
      await getRoleList().then((re) => {
        if (re.isSuccess) {
          setRoleLis(re.data);
        }
      });

      await getOrgTre().then((re) => {
        if (re.isSuccess) {
          setOrgTre(re.data);
        }
      });
    };
    initData();
  }, []);




  const stateEnum = new Map();
  stateEnum.set(0, { text: '禁用', status: 'Error' });
  stateEnum.set(1, { text: '启用', status: 'Success' });
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: '规则名称是唯一的key',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '账号',
      dataIndex: 'account',
      valueType: 'textarea',
    },
    {
      title: '昵称',
      dataIndex: 'name',
      valueType: 'textarea',
    },
    {
      title: '电话',
      dataIndex: 'phone',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '组织',
      dataIndex: 'orgId',
      valueType: 'textarea',
      fieldProps: {
        options: orgTre,
        fieldNames: {
          children: 'children',
          label: 'value',
          value: 'key',
        },
      },
      valueType: 'treeSelect',
    },
    {
      title: '角色',
      dataIndex: 'roleId',
      valueEnum: () => {
        const list = {};
        roleLis?.map((item) => {
          list[item.key] = { text: item.value };
        });
        return list;
      },
    },
    {
      title: '状态',
      dataIndex: 'state',
      valueEnum: stateEnum,
    },
    {
      title: '到期时间',
      dataIndex: 'expirationTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      valueType: 'date',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <AuthorityButton
          type={'link'}
          key="Info"
          class={'Info'}
          text={'详情'}
          onClick={() => {
            setState('read');
            setModalVisit(true);
            formRef?.current?.setFieldsValue(record);
          }}
        />,
        <AuthorityButton
          type={'link'}
          key="update"
          class={'update'}
          text={'修改'}
          onClick={() => {
            setState('edit');
            setModalVisit(true);
            formRef?.current?.setFieldsValue(record);
          }}
        />,
        <AuthorityButton
          type={'popconfirm'}
          key="del"
          class={'delete'}
          text={'删除'}
          onConfirm={() => {
            del([record.id]).then((re) => {
              if (re.isSuccess) {
                message.success(re.msg);
                actionRef.current.reload();
              } else {
                message.error(re.msg);
              }
            });
          }}
        />,
      ],
    },
  ];
  const intl = useIntl();
  return (
    <PageContainer>
      <ProTable
        headerTitle="租户"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          // eslint-disable-next-line react/jsx-key
          <AuthorityButton
            class={'Add'}
            text={'新增'}
            onClick={() => {
              setState('edit');
              setModalVisit(true);
              formRef?.current?.resetFields();
            }}
          />,
        ]}
        request={async (params) => {
          var queryData = [];
          var total = 0;
          await page(JSON.stringify(params)).then((re) => {
            queryData = re.data.data;
            total = re.data.total;
          });
          return {
            data: queryData,
            success: true,
            total: total,
          };
        }}
        columns={columns}
        pagination={{ defaultPageSize: 10 }}
      />
      {/* ------------------------ */}

      <ModalForm
        actionRef={actionRef}
        modalVisit={modalVisit}
        setModalVisit={setModalVisit}
        state={state}
        formRef={formRef}
        roleLis={roleLis}
        orgTre={orgTre}
        onClose={() => {
          setModalVisit(false);
        }}
      />
    </PageContainer>
  );
};

export default Tenant;
